<?php
class UploadController extends Controller {
/*	
	public function actions()
	{
		$dir = Yii::app() -> getBasePath() . "/../public/uploads" . date ( 'Y' ) . '/' . date ( 'm' );
		if (! is_dir ( $dir ))
			mkdir ( $dir, 0777, 1 );
		
		return array(
				'upload'=>array(
						'class'=>'xupload.actions.XUploadAction',
						'path' => $dir,
						'publicPath' => $dir,
				),
		);
	}
*/	
	function actionIndex() {
		$dir = '/mnt/hgfs/PHP/vxwebsite/public/' . date ( 'Y' ) . '/' . date ( 'm' );
		if (! is_dir ( $dir ))
			mkdir ( $dir, 0777, 1 );
		$uploaded = false;
		$model = new Upload ();
		if (isset ( $_POST ['Upload'] )) {
			$model->attributes = $_POST ['Upload'];
			$file = CUploadedFile::getInstance ( $model, 'file' );
			$newName = substr ( md5 ( $file->extensionName . round ( (microtime ( true ) * 1000) ) ), 0, 17 ) . '.' . $file->extensionName;
			$file_name = $dir . '/' . $newName;
			if ($model->validate ()) {
				$uploaded = $file->saveAs ( $file_name, TRUE );
			}
		}
		
		$this->render ( 'index', array (
				'model' => $model,
				'uploaded' => $uploaded,
				'dir' => $dir,
				//'filename' => $file_name
				) );
	}
	
	
	public function actionTest()
	
	{
		$model = new Upload();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$type = isset($_GET['type']) ? $_GET['type'] : 'post';
	
		if (isset($_POST['Photo'])) {
	
			$model->attributes = $_POST['Photo'];
	
			$photos = CUploadedFile::getInstancesByName('photos');
	
			// proceed if the images have been set
			if (isset($photos) && count($photos) > 0) {
	
				// go through each uploaded image
				foreach ($photos as $image => $pic) {
					echo $pic->name.'<br />';					
				}
			}
				
		}
		$this->render('test', array(
				'model' => $model,
	
		));
	
	}
	
	public function actionTest2(){
		$model = new Upload();
    	Yii::import( "xupload.models.XUploadForm" );
    	$photos = new XUploadForm;
    	$this->render( 'test2', array(
        'model' => $model,
        'photos' => $photos,
    	));
		
	}
	
	
	public function createimage($width,$height,$destination,$thumbpath,$type){
		$obj_imgl = new thumbnail_images;
		$obj_imgl->PathImgOld = $destination.".".$type;
		$obj_imgl->PathImgNew = $thumbpath.'.'.$type;
		$obj_imgl->NewWidth = $width;
		if($height!=''){
			$obj_imgl->NewHeight = $height;
		}
		if (!$obj_imgl->create_thumbnail_images())
			echo "error";
	}
	

	
	public function actionUpload( ) {
		
		$uploadpath = Yii::app() -> getBasePath() . "/../public/uploads/" . date ( 'Y' ) . '/' . date ( 'm' ) . '/';
		$thumbpath = $uploadpath.'thumb'.'/';
		if (! is_dir ( $uploadpath ))
			mkdir ( $uploadpath, 0777, 1 );
		
		if (! is_dir ( $thumbpath ))
			mkdir ( $thumbpath, 0777, 1 );
		
		Yii::import( "xupload.models.XUploadForm" );
		//Here we define the paths where the files will be stored temporarily
		$path = $uploadpath;
		$publicPath = Yii::app( )->getBaseUrl( ).'/public/uploads/'. date ( 'Y' ) . '/' . date ( 'm' ) . '/';
	
		//This is for IE which doens't handle 'Content-type: application/json' correctly
		header( 'Vary: Accept' );
		if( isset( $_SERVER['HTTP_ACCEPT'] )
				&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
					header( 'Content-type: application/json' );
				} else {
					header( 'Content-type: text/plain' );
				}
	
				//Here we check if we are deleting and uploaded file
				if( isset( $_GET["_method"] ) ) {
					if( $_GET["_method"] == "delete" ) {
						if( $_GET["file"][0] !== '.' ) {
							$file = $path.$_GET["file"];
							if( is_file( $file ) ) {
								unlink( $file );
							}
						}
						echo json_encode( true );
					}
				} else {
					$model = new XUploadForm;
					$model->file = CUploadedFile::getInstance( $model, 'file' );
					//We check that the file was successfully uploaded
					if( $model->file !== null ) {
						//Grab some data
						$model->mime_type = $model->file->getType( );
						$model->size = $model->file->getSize( );
						$model->name = $model->file->getName( );
						//(optional) Generate a random name for our file
						$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
						$filetype = $model->file->getExtensionName( );				
						if( $model->validate( ) ) {
							//Move our file to our temporary dir
							$model->file->saveAs( $path.$filename.'.'.$filetype );
							chmod( $path.$filename.'.'.$filetype, 0777 );
							//here you can also generate the image versions you need
							//using something like PHPThumb
	
							Yii::import('application.extensions.ThumbnailImages.thumbnail_images');

							$this->createimage(100,'', $path.$filename,$thumbpath.$filename,$filetype);						
							//$this->createimage(240,'',$destination,'m',$type);
							//$this->createimage(600,'',$destination,'l',$type);
								
							//Now we need to save this path to the user's session
							if( Yii::app( )->user->hasState( 'images' ) ) {
								$userImages = Yii::app( )->user->getState( 'images' );
							} else {
								$userImages = array();
							}
							$userImages[] = array(
									"path" => $path.$filename.$filetype,
									//the same file or a thumb version that you generated
									"thumb" => $thumbpath.$filename.$filetype,
									"filename" => $filename.$filetype,
									'size' => $model->size,
									'mime' => $model->mime_type,
									'name' => $model->name,
							);
							Yii::app( )->user->setState( 'images', $userImages );
	
							//Now we need to tell our widget that the x was succesfull
							//We do so, using the json structure defined in
							// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
							echo json_encode( array( array(
									"name" => $model->name,
									"type" => $model->mime_type,
									"size" => $model->size,
									"url" => $publicPath.$filename.'.'.$filetype,
									"thumbnail_url" => $publicPath."thumb/$filename.$filetype",
									"delete_url" => $this->createUrl( "upload", array(
											"_method" => "delete",
											"file" => $filename.$filetype
									) ),
									"delete_type" => "POST"
							) ) );
						} else {
							//If the upload failed for some reason we log some data and let the widget know
							echo json_encode( array(
									array( "error" => $model->getErrors( 'file' ),
									) ) );
							Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
							CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
									);
						}
					} else {
						throw new CHttpException( 500, "Could not upload file" );
					}
				}
	}
	
	
	
}